package com.example.langchain4j.service;

import cn.hutool.json.JSONUtil;
import com.deepoove.poi.XWPFTemplate;
import com.example.langchain4j.common.constant.PromptConstant;
import com.example.langchain4j.common.exception.BusinessException;
import com.example.langchain4j.utils.DocumentUtils;
import dev.langchain4j.model.chat.ChatLanguageModel;
import dev.langchain4j.model.chat.response.ChatResponse;
import dev.langchain4j.model.input.Prompt;
import dev.langchain4j.model.input.PromptTemplate;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class JiTiYiAnService {

    @Resource
    @Qualifier("chatLanguageModel")
    private ChatLanguageModel chatLanguageModel;

    private static final String GENERATED_DIR = "src/main/resources/generated";

    public Map<String, Object> generationJiTiYiAn(MultipartFile file1, MultipartFile file2, HttpServletResponse response) {
        try {
            // 提取文档内容
            String document1Content = DocumentUtils.extractTextFromWord(file1);
            String document2Content = DocumentUtils.extractTextFromWord(file2);

            // 创建提示模板
            String generalJianYaoAnQing = PromptConstant.generalJianYaoAnQing;
            PromptTemplate promptTemplate1 = PromptTemplate.from(generalJianYaoAnQing);
            HashMap<String, Object> vary1 = new HashMap<>();
            vary1.put("document1Content", document1Content);
            vary1.put("document2Content", document2Content);
            Prompt prompt1 = promptTemplate1.apply(vary1);

            // 调用模型 获取简要案情
            ChatResponse chatResponse1 = chatLanguageModel.chat(prompt1.toUserMessage());
            String jianyaoanqingRes = chatResponse1.aiMessage().text();
            log.info("------------------------------------------------------------------------------------");
            log.info("生成的简要案情描述：{}", jianyaoanqingRes);

            // 结合简要案情描述 调用模型 生成json
            String generalShenpibiaoJson = PromptConstant.generalShenpibiaoJson;
            vary1.put("jianyaoanqingRes", jianyaoanqingRes);
            PromptTemplate promptTemplate2 = PromptTemplate.from(generalShenpibiaoJson);
            Prompt prompt2 = promptTemplate2.apply(vary1);
            ChatResponse chatResponse2 = chatLanguageModel.chat(prompt2.toUserMessage());
            String shenpibiaoJsonRes = chatResponse2.aiMessage().text();

            log.info("生成的json：{}", shenpibiaoJsonRes);

            // 确保generated目录存在
            java.nio.file.Path generatedPath = java.nio.file.Paths.get(GENERATED_DIR);
            if (!java.nio.file.Files.exists(generatedPath)) {
                java.nio.file.Files.createDirectories(generatedPath);
            }

            // 生成文件名
            java.time.format.DateTimeFormatter formatter = java.time.format.DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss");
            String timestamp = java.time.LocalDateTime.now().format(formatter);
            String fileName = "行政处罚立案审批表_" + timestamp + ".docx";
            String filePath = GENERATED_DIR + "/" + fileName;


            // 填充word模板并保存到文件
            Map<String, Object> resultMap = JSONUtil.toBean(shenpibiaoJsonRes, Map.class);
            ClassPathResource resource = new ClassPathResource("集体议案template.docx");
            InputStream templateInputStream = resource.getInputStream();
            XWPFTemplate template = XWPFTemplate.compile(templateInputStream).render(resultMap);

            // 保存到本地文件
            java.io.FileOutputStream fileOut = new java.io.FileOutputStream(filePath);
            template.write(fileOut);
            fileOut.close();
            template.close();

            log.info("集体议案文件已保存: {}", filePath);

            // 准备返回结果
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("fileName", fileName);
            result.put("filePath", "http://localhost:8018/api/dify/generated/" + fileName);
            result.put("jsonData", shenpibiaoJsonRes);
            result.put("message", "集体议案生成成功");

            log.info("集体议案生成完成，返回结果: {}", result);
            return result;

        }catch (IOException e){
            log.error("解析文档失败", e);
            throw new BusinessException(500,"解析文档失败: " + e.getMessage());
        }catch (Exception e) {
            log.error("生成审批表失败", e);
            throw new BusinessException(500, "生成审批表失败: " + e.getMessage());
        }
    }
}
